package com.example.myshopping3.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myshopping3.model.Book;
import com.example.myshopping3.model.Comment;
import com.example.myshopping3.model.Result;
import com.example.myshopping3.model.view.CommentView;
import com.example.myshopping3.service.BookService;
import com.example.myshopping3.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private CommentService commentService;

    /**
     * Reslful风格:
     * 从服务端获取数据--->get请求------>GetMapping
     * 向服务端推送数据---->post请求----->PostMapping
     * 修改服务端数据------>put请求---->PutMapping
     * 移除服务端中的数据----->delete请求---->DeleteMapper
     *
     * @return
     */
//    @GetMapping("/queryBooks")
//    public List<Book> queryBooks() {
//        //获得所有图书列表
//        List<Book> bookList = bookService.list();
//        return bookList;
//    }
//
//    @GetMapping("/findBookById/{bookId}")
//    public Book findBookById(@PathVariable int bookId) {
//        Book book = bookService.getById(bookId);
//        return book;
//    }

    /**
     * 添加redis缓存之后的代码
     *
     * @return
     */
    @GetMapping("/queryBooks")
    public List<Book> queryBooks() {
        return bookService.list(); // 调用重写的缓存方法
    }

    @GetMapping("/findBookById/{bookId}")
    public Book findBookById(@PathVariable int bookId) {
        return bookService.getById(bookId); // 调用重写的缓存方法
    }


    @GetMapping("/getComment/{bookId}")
    public List<CommentView> getComment(@PathVariable int bookId) {
        List<CommentView> commentList = commentService.getComment(bookId);
        commentList.forEach(System.out::println);
        return commentList;
    }

    @PostMapping("/addComment")
    public Result addComment(@RequestBody Comment comment) {
        boolean boo = commentService.save(comment);
        System.out.println(boo);
        if (boo) {
            Result rs = Result.success("评论添加成功", null);
            System.out.println(rs);
            return rs;
        }
        return Result.failt(500, "评论添加失败", null);
    }


    /**
     * 更新数据
     * 在数据变更后操作调用
     * @param book
     */
    @PostMapping("/updateBook")
    public void updateBook(@RequestBody Book book) {
        bookService.updateById(book);
        bookService.clearBookCache(book.getBookId());
    }
}
